﻿/*========================== 
 * @author 郑金泉
 * @desc 时间实用工具
 * ========================= */
using System;
using System.Collections.Generic;
using System.Text;

namespace Obsidian.Utils
{
    public class DateTimeUtil
    {
        private static readonly DateTime Jan1st1970 = new DateTime
            (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        public static string NowString
        {
            get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }
        }

        public static long CurrentTimeMillis
        {
            get
            {
                double millis = (DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
                return (long)millis;
            }
        }

        /// <summary>
        /// 转换为Unix时间戳
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToUnixTimeStamp(DateTime dt)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            TimeSpan ts = dt.Subtract(dtStart);
            string timeStamp = ts.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return timeStamp;
        }

        /// <summary>
        /// Unix时间戳转换为DateTime
        /// </summary>
        /// <param name="unixTimeStamp"></param>
        /// <returns></returns>
        public static DateTime FromUnixTimeStamp(string unixTimeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(unixTimeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

    }
}
